package net.qhzw.geologr5.gis.auth.exception;

import com.alibaba.fastjson.JSON;
import net.qhzw.geologr5.gis.common.framework.exception.CustomException;
import net.qhzw.geologr5.gis.common.framework.utils.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

public class CustomWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {


    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        Class<? extends Exception> aClass = e.getClass();

        ResponseEntity<OAuth2Exception> responseEntity = null;
        try {
            responseEntity = super.translate(e);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        JsonResult jsonResult = new JsonResult();
        OAuth2Exception body = responseEntity.getBody();
        if (e instanceof InvalidGrantException) {
            return new ResponseEntity(jsonResult.error(402, "密码不正确"), HttpStatus.PAYMENT_REQUIRED);
        } else if (e instanceof InvalidTokenException) {
            return new ResponseEntity(jsonResult.error(401, "token已失效"), HttpStatus.OK);
        } else if (e instanceof UsernameNotFoundException) {
            return new ResponseEntity(JsonResult.error(405, body.getLocalizedMessage()), HttpStatus.METHOD_NOT_ALLOWED);
        } else if (e instanceof CustomException) {
            return new ResponseEntity(JsonResult.error(405, body.getLocalizedMessage()), HttpStatus.METHOD_NOT_ALLOWED);
        } else {
            String localizedMessage = body.getLocalizedMessage();
            if (localizedMessage.contains("不存在")) {
                return new ResponseEntity(JsonResult.error(405, body.getLocalizedMessage()), HttpStatus.METHOD_NOT_ALLOWED);
            }
            if (localizedMessage.contains("已锁定")) {
                return new ResponseEntity(JsonResult.error(403, body.getLocalizedMessage()), HttpStatus.FORBIDDEN);
            }
            return new ResponseEntity(JsonResult.error(401, body.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
        }

    }


}
